﻿using Common.AspNetCore;
using Common.Infrastructure;
using File.Api.Models;
using File.Api.Service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace File.Api.Controllers
{
    [Route("api/Download")]
    public class DownloadController : ApiController
    {
        private readonly DownloadFileService downloadFileService;

        public DownloadController(IServiceProvider provider, DownloadFileService auth)
             : base(provider)
        {
            this.downloadFileService = auth;
        }

        [HttpPost, Route("DownloadFile")]
        public async Task<ApiActionResult<DownFileModel>> DownloadFile([FromBody] FileDownloadByIdParamModel model)
        {
            return await SafeExecuteAsync<DownFileModel>(async (param) =>
            {
                if (model == null || !model.Ids.Any())
                {
                    return new DownFileModel();
                }

                return await this.downloadFileService.DownloadFileAsync(model.Ids);
            });
        }

        [HttpGet, Route("DownloadFile")]
        public async Task DownloadFile(string id)
        {
            try
            {
                List<string> ids = new List<string>() { id };
                var ret = await this.downloadFileService.DownloadFileAsync(ids);
                var d = ret != null && ret.Details.Any() ? ret.Details[0] : null;
                if (d != null && d.FileData != null && d.FileData.Any())
                {
                    await SetDataAsync(d.FileName, d.FileType, d.FileData);
                }
                else if (d != null)
                {
                    await SetDataAsync(d.FileName, d.FileType, null);
                }
            }
            catch
            {
            }
        }

        [HttpGet, Route("ShowFile")]
        public async Task ShowFile(string id)
        {
            try
            {
                List<string> ids = new List<string>() { id };
                var ret = await this.downloadFileService.DownloadFileAsync(ids);
                var d = ret != null && ret.Details.Any() ? ret.Details[0] : null;
                if (d != null && d.FileData != null && d.FileData.Any())
                {
                    await SetDataByShowAsync(d.FileName, d.FileType, d.FileData);
                }
                else if (d != null)
                {
                    await SetDataByShowAsync(d.FileName, d.FileType, null);
                }
            }
            catch
            {
            }
        }

        private async Task SetDataAsync(string fileName, string contentType, byte[] data)
        {
            var httpResponse = this.Response;
            httpResponse.ContentType = contentType;
            string encodeFilename = System.Net.WebUtility.UrlEncode(fileName);
            httpResponse.Headers.Add("Content-Disposition", "attachment;filename=" + encodeFilename);
            if (data != null && data.Any())
            {
                await httpResponse.BodyWriter.WriteAsync(data);
            }

            await httpResponse.BodyWriter.FlushAsync();
        }

        private async Task SetDataByShowAsync(string fileName, string contentType, byte[] data)
        {
            var httpResponse = this.Response;
            httpResponse.ContentType = contentType;
            if (data != null && data.Any())
            {
                await httpResponse.BodyWriter.WriteAsync(data);
            }

            await httpResponse.BodyWriter.FlushAsync();
        }
    }
}
